package com.cnyz.controller;

import cn.hutool.core.util.ObjectUtil;
import com.cnyz.base.PageResponse;
import com.cnyz.base.ResponseResult;
import com.cnyz.dto.LoginDto;
import com.cnyz.dto.UserDto;
import com.cnyz.entity.User;
import com.cnyz.exception.BaseException;
import com.cnyz.service.CustomerService;
import com.cnyz.utils.UserThreadLocal;
import com.cnyz.vo.LoginVo;
import com.cnyz.vo.UserVo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/customer")
@ApiModel(description = "用户管理接口")
public class CustomerController {

    //用户登录注册重置密码

    @Autowired
    private CustomerService customerService;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String fromEmail;


    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ResponseResult register(@RequestBody UserDto userDto) {

        if(ObjectUtil.isEmpty(userDto.getCode())) {
            return ResponseResult.error("验证码不能为空");
        }

        if(!ObjectUtil.equals(userDto.getCode(),redisTemplate.opsForValue().get(userDto.getEmail()))){
            return ResponseResult.error("验证码错误");
        }

        Long id=customerService.insertCustomer(userDto);
        return ResponseResult.success("注册成功",id);
    }


    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseResult<LoginVo> login(@RequestBody LoginDto loginDto) {

        LoginVo loginVo = customerService.login(loginDto);
        UserThreadLocal.set(loginDto.getId());// 将用户ID存入线程本地变量，方便后续使用
        return ResponseResult.success(loginVo);
    }

    @PostMapping("/reset-password")
    @ApiOperation("重置密码")
    public ResponseResult resetPassword(@RequestBody UserDto userDto) {
        if(ObjectUtil.isEmpty(userDto.getCode())) {
            return ResponseResult.error("验证码不能为空");
        }

        if(!ObjectUtil.equals(userDto.getCode(),redisTemplate.opsForValue().get(userDto.getEmail()))){
            return ResponseResult.error("验证码错误");
        }

       customerService.resetPassword(userDto);
        return ResponseResult.success("密码重置成功");
    }

    @PostMapping("/email")
    @ApiOperation("发送邮箱验证码")
    public ResponseResult sendEmail(@RequestParam String email) {
        String code = String.valueOf((int) (Math.random() * 9000 + 1000)); // 生成四位随机验证码
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(email);
        message.setSubject("在线学习系统提醒您");
        message.setText("您的验证码是：" + code + "用于学习平台身份验证，5分钟内有效，请勿泄露和转发。如非本人操作，请忽略此短信。");

        try{
            mailSender.send(message);
            // 将验证码存入Redis，设置过期时间为5分钟
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
        } catch (MailException e) {
           throw  new BaseException("发送验证码失败，请稍后再试");
        } catch (Exception e) {
            throw new BaseException("发送验证码失败，请稍后再试");
        }

        return ResponseResult.success("验证码已发送到邮箱",code);
    }

    //用户相关信息增删改查

    @GetMapping("/user/email")
    @ApiOperation("通过邮箱获取用户信息")
    public ResponseResult<UserVo> getUserByEmail(@RequestParam String email) {
        UserVo userVo = customerService.getUserByEmail(email);
        if (userVo == null) {
            return ResponseResult.error("用户不存在");
        }
        return ResponseResult.success("获取用户信息成功", userVo);
    }

    @GetMapping("/user/id")
    @ApiOperation("通过ID获取用户信息")
    public ResponseResult<UserVo> getUserById(@RequestParam Long id) {
        UserVo userVo = customerService.getUserById(id);
        if (userVo == null) {
            return ResponseResult.error("用户不存在");
        }
        return ResponseResult.success("获取用户信息成功", userVo);
    }

    @GetMapping("/user/page")
    @ApiOperation("分页查询用户信息")
    public ResponseResult<PageResponse<UserVo>> getUserPage(
            @RequestParam(value = "page", defaultValue = "1") int pageNum,
            @RequestParam(value = "size", defaultValue = "10") int pageSize,
            @RequestParam(value = "type", required = false) Integer role,
            @RequestParam(value = "username", required = false) String username) {
        return ResponseResult.success("获取用户分页信息成功",customerService.getUserPage(pageNum,pageSize,role,username));
    }//能够选择类型去分页查询

    @DeleteMapping("/user/id")
    @ApiOperation("通过ID删除用户")
    public ResponseResult deleteUserById(@RequestParam Long id) {
    UserVo userVo = customerService.getUserById(id);
        if (userVo == null) {
            return ResponseResult.error("用户不存在");
        }

        customerService.deleteUserById(id);
        return ResponseResult.success("用户删除成功");
    }

}
